package com.vic.sb08.controller;

import com.vic.sb08.entity.User;
import com.vic.sb08.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 *
 * @author Victor
 * date: 2019/5/6 15:56
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("test")
    public String test() {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    @GetMapping("test2")
    public String test2() {
//        new Thread(() -> {
//            while (true) {
//                System.out.println("aaaa");
//            }
//        }).start();
        return "ok";
    }

    @GetMapping("mock")
    public String saveUser(/*@RequestBody User user*/){

        for(int i = 0; i < 30; i++) {
            User u = new User();
            u.setGmtCreated(new Date());
            u.setGmtModified(new Date());
            u.setName("name"+i);
            u.setPassword("p"+i);
            u.setStatus(1);
            u.setPhone("phone"+i);
            int random = new Random().nextInt(20);
            if(random < 26)
                u.setUserType(1);
            else
                u.setUserType(2);
            userRepository.save(u);
        }
        return "ok";
    }

    @GetMapping("findByName")
    public List<User> findByName(@RequestParam("name") String name){
        return userRepository.findByName(name);
    }

    @GetMapping("findById")
    public User findById(@RequestParam("id") Long id){
        Optional<User> byId = userRepository.findById(id);
        return byId.get();
    }

    @GetMapping("findByNameLike")
    public List<User> findByNameLike(@RequestParam("name") String name){
        return userRepository.findByNameLike(name);
    }

    @GetMapping("findByPage")
    public Page<User> findByPage(@RequestParam("userType") Integer userType){
        return userRepository.findByUserType(userType, new PageRequest(1, 5));
    }

}
